package com.jzg.jcptadmin.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.adpter.OfflineDetectionAdapter;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.LocalData;
import com.jzg.jcptadmin.data.vo.OfflineDetectionData;
import com.jzg.jcptadmin.data.vo.PopListDataModel;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.OfflineDetectionPresenter;
import com.jzg.jcptadmin.view.PopWindowView;
import com.jzg.jcptadmin.viewinterface.OfflineDetectionInterface;
import com.jzg.template.refreshrecycleview.DividerItemDecoration;
import com.jzg.template.refreshrecycleview.RefreshBaseAdapter;
import com.jzg.template.refreshrecycleview.RefreshRecycleView;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 评估师端专业线下检测列表界面
 * OfflineDetectionActivity
 *
 * @author sunbl
 *         created at 2016/1/21 16:09
 */
public class OfflineDetectionActivity extends BaseActivity implements View.OnClickListener, RefreshRecycleView.OnStateChangeLstener, OfflineDetectionInterface {
    @Bind(R.id.fast_title_defaultsort)
    TextView filter_date;
    @Bind(R.id.fast_advanced_filter)
    TextView filter_status;
    @Bind(R.id.fast_hintline)
    View fastHintline;
    @Bind(R.id.fast_empty_view)
    ViewStub fastEmptyView;
    @Bind(R.id.fast_online_recycler)
    RefreshRecycleView proOfflineRecycler;
    @Bind(R.id.title_content)
    TextView titleContent;
    @Bind(R.id.title_searchbyvin)
    ImageView search;
    private PopWindowView pop;
    private List<OfflineDetectionData.OffLineTaskListEntity> mDatas = new ArrayList<>();
    private OfflineDetectionAdapter adapter;
    private OfflineDetectionPresenter presenter;
    private StatusData statusData;
    private OfflineDetectionData.OffLineTaskListEntity currEntity;
    //    private int status;
    //数据类型 2今日任务  3昨天任务  1全部任务 默认今日任务
    private int datetype = Constant.ALL_TASK;
    //点击全部状态的id  默认-2
    private String status = "-2";
    //刷新-第一个条目ID   加载-最后一个条目ID
    private int PageId;
    /**
     * (0默认，1刷新，2加载
     */
    private int Operation = 0;
    User user;
    private String[] youmeng = new String[]{"pinggushi_xianxiaquanbuzhuangtai", "pinggushi_xianxiadaipingguzhuangtai", "pinggushi_xianxiachaoshizhuangtai",
            "pinggushi_xianxiayiquerenzhuangtai", "pinggushi_xianxiabeibohuizhuangtai", "pinggushi_xianxiayipingguzhuangtai", "pinggushi_xianxiayishenhezhuangtai",
            "pinggushi_xianxiayiqianshouzhuangtai", "pinggushi_xianxiayishanchuzhuangtai"};//友盟统计埋点

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_detection);
        ButterKnife.bind(this);
        titleContent.setText("专业线下检测");
        user = appContext.getUser();
        filter_date.setText("全部任务");
        search.setVisibility(View.VISIBLE);
//        pop = new PopWindowView(this, filter_date, filter_status, fastHintline);
        Drawable drawable = getResources().getDrawable(R.drawable.down_arror);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        pop = new PopWindowView(this, filter_date, filter_status, fastHintline, drawable);
        DataManager dataManager = DataManager.getInstance();
        presenter = new OfflineDetectionPresenter(dataManager);
        presenter.attachView(this);
        //默认加载列表
//        presenter.loadOffineDataNew(user.getUserId() + "", datetype + "", status, Operation + "", "");
        //加载状态
        statusData = appContext.getStatus();
        initData();
//        showDialog();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        onRefresh();
    }


    private void setPopDataByStatus() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();
        for (int i = 0; i < statusData.getItemList().getStatusInfo().getItem().size(); i++) {
            String value = statusData.getItemList().getStatusInfo().getItem().get(i).getValue();
            String valueID = statusData.getItemList().getStatusInfo().getItem().get(i).getId();
            if (i == 0) {
                mSortList.add(new PopListDataModel(value, valueID, R.color.text_blue));
            } else {
                mSortList.add(new PopListDataModel(value, valueID, R.color.light_grey_text));
            }
        }
        pop.setData(mSortList);
    }

    private void setPopDataByDate() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();
        mSortList.add(new PopListDataModel("全部任务", "0", R.color.light_grey_text));
        mSortList.add(new PopListDataModel("今日任务", "1", R.color.text_blue));
        mSortList.add(new PopListDataModel("昨日任务", "2", R.color.light_grey_text));
        pop.setData(mSortList);
    }

    public Integer op;

    private void initData() {
        proOfflineRecycler.setColorSchemeColors(Color.parseColor(Constant.ACTIVITY_REFRESHCOLOR));
        proOfflineRecycler.setOnStateChangeLstener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        proOfflineRecycler.mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        proOfflineRecycler.setLayoutManager(linearLayoutManager);
        if (adapter == null) {
            adapter = new OfflineDetectionAdapter(this, mDatas);
        }
        proOfflineRecycler.setAdapter(adapter);
        adapter.setOnItemClickLitener(new RefreshBaseAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {//
                if (position == mDatas.size()) {
                    onBottom();
                } else {
                    currEntity = mDatas.get(position);
                    String operation = currEntity.getMessageOperation();

                    try {
                        op = Integer.valueOf(operation);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SweetAlertDialog sweetDialog = new SweetAlertDialog(OfflineDetectionActivity.this);
                    String title = "";
                    String content = "";
                    String confirmText = "";
                    String cancelText = "";
                    SweetAlertDialog.OnSweetClickListener confirmListener = new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            String status = currEntity.getStatus();
                            if (op == 8 || op == 4) {
                                presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "ShenHeRenling", op);
                            } else if (op == 3) {
                                presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "renling", -1);
                            } else {
                                if ("2".equals(status)) {
                                    toDetail();
                                } else {
                                    presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "renling", op);
                                }
                            }
                        }
                    };
                    SweetAlertDialog.OnSweetClickListener cancelListener = new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    };
                    if (op != 6) {
                        switch (op) {
                            case 1://待评估
                                title = "确认任务";
                                content = "车牌号:" + currEntity.getCarLicense() + "\r\n"
                                        + "VIN:" + currEntity.getVin() + "\r\n"
                                        + "联系人:" + currEntity.getLikeMan() + "\r\n"
                                        + "联系方式:" + currEntity.getLikeTel() + "\r\n"
                                        + "品牌:" + currEntity.getMakeName() + "\r\n"
                                        + "车型:" + currEntity.getModelName() + "\r\n"
                                        + "车系:" + currEntity.getStyleName();
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 2://待评估，被别人退回
                                content = "此订单之前由" + currEntity.getNickname() + "退回！是否操作此订单？" + "\r\n" + "\r\n" + (TextUtils.isEmpty(currEntity.getTaskBackReason()) ? "" : currEntity.getTaskBackReason());//.replace("<br/><br/>","\r\n")
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 3://已认领过 （总部评估师）
                                content = "此订单已被" + currEntity.getNickname() + "认领！是否操作此订单？";
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 4://总部审核（被驳回过）
                                content = "此订单之前由" + currEntity.getShenheName() + "审核驳回！是否操作此订单？" + "\r\n" + "\r\n" + (TextUtils.isEmpty(currEntity.getAppraiseBackReason()) ? "" : currEntity.getAppraiseBackReason());//.replace("<br/><br/>","\r\n")
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 5://已认领（非总部）
                                content = "此订单已被" + currEntity.getNickname() + "认领!";
                                confirmText = "关闭";
                                break;
                            case 7://此订单正在被孙某某审核！
                                content = "此订单正在被" + currEntity.getShenheName() + "审核!";
                                confirmText = "关闭";
                                break;
                            case 8://弹出是否确认审核
                                title = "确认审核";
                                content = "是否确认审核该订单?";
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                        }
                        sweetDialog.setTitleText(title);
                        if (!TextUtils.isEmpty(title)) {
                            sweetDialog.setTitleText(title);
                        }
                        if (!TextUtils.isEmpty(content)) {
                            sweetDialog.setContentText(content);
                        }
                        if (!TextUtils.isEmpty(confirmText)) {
                            sweetDialog.setConfirmText(confirmText);
                            if ("5".equals(operation) || "7".equals(operation))
                                sweetDialog.setConfirmClickListener(cancelListener);
                            else
                                sweetDialog.setConfirmClickListener(confirmListener);
                        }
                        if (!TextUtils.isEmpty(cancelText)) {
                            sweetDialog.setCancelText(cancelText);
                            sweetDialog.setCancelClickListener(cancelListener);
                        }
                        sweetDialog.show();
                    } else {
                        toDetail();
                    }
                }
            }
        });
    }

    private void toDetail() {
        LocalData.isRefresh = true;
        Intent intent = new Intent(OfflineDetectionActivity.this, TaskViewActivity.class);
        intent.putExtra(Constant.ACTIVITY_OFFINEID, currEntity.getID());
        startActivity(intent);
    }

    @OnClick({R.id.title_searchbyvin,R.id.fast_title_defaultsort, R.id.fast_advanced_filter})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fast_title_defaultsort:
                setPopDataByDate();
                pop.controlPopWindowShow(filter_date, filter_status);
                //动态显示右侧的箭头
                Drawable drawable = getResources().getDrawable(R.drawable.up_arror);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                filter_date.setCompoundDrawables(null, null, drawable, null);//画在右边
                break;
            case R.id.fast_advanced_filter:
                if (statusData != null) {
                    setPopDataByStatus();
                    pop.controlPopWindowShow(filter_status, filter_date);
                } else {
                    MyToast.showShort("无筛选条件");
                }
                //动态显示右侧的箭头
                Drawable drawable1 = getResources().getDrawable(R.drawable.up_arror);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); //设置边界
                filter_status.setCompoundDrawables(null, null, drawable1, null);//画在右边
                break;
            case R.id.title_searchbyvin:
                Bundle bd = new Bundle();
                bd.putInt("source",2);
                ActivityHelp.startActivity(this,OffLineSearchByVINActivity.class,"bd",bd);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (LocalData.isRefresh && appContext.isNetWork) {
            proOfflineRecycler.post(new Runnable() {
                @Override
                public void run() {
                    proOfflineRecycler.setRefreshing(true);
                }
            });
            LocalData.isRefresh = false;//
            onRefresh();
        } else {
            proOfflineRecycler.setRefreshing(false);//停止显示加载动画
            if (mDatas!=null && mDatas.size()>0){
                dismissDialog();
            }else{
                showEmptyView(Constant.errr_net);
            }
        }
//        onRefresh();
    }

    //下拉刷新
    @Override
    public void onRefresh() {
        presenter.resetPageIndex();
        Operation = Constant.LISTVIEW_DEFAULT;
        if (appContext.isNetWork) {
            presenter.loadOffineDataNew(user.getUserId() + "", datetype + "", status + "", Operation + "", "");
        } else {
            proOfflineRecycler.setRefreshing(false);
            if (mDatas!=null && mDatas.size()>0){
                dismissDialog();
                MyToast.showShort(Constant.errr_net);
            }else{
                showEmptyView(Constant.errr_net);
            }
        }
    }

    @Override
    public void onBottom() {
        //加载更多
        Operation = Constant.LISTVIEW_LOAD_MORE;
        if (mDatas.size() > 0) {
            presenter.loadOffineDataNew(user.getUserId() + "", datetype + "", status + "", Operation + "", mDatas.get(mDatas.size() - 1).getID());
        } else {
            proOfflineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        LocalData.isRefresh = true;//打开刷新
        if (presenter != null)
            presenter.detachView();
    }

    //默认联网返回的数据
    @Override
    public void showDatas(OfflineDetectionData datas) {
        //联网成功关闭刷新进度条
        dismissDialog();
        proOfflineRecycler.setRefreshing(false);
        if (datas.getOffLineTaskList().size() == 0) {
            fastEmptyView.setVisibility(View.VISIBLE);
            proOfflineRecycler.setVisibility(View.GONE);
        } else {
            fastEmptyView.setVisibility(View.GONE);
            proOfflineRecycler.setVisibility(View.VISIBLE);
            if (Operation == 0 || Operation == 1) {
                mDatas.clear();
                mDatas.addAll(datas.getOffLineTaskList());
                Operation = 0;
            }
            adapter.UpDateList(mDatas);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 加载更多返回的数据
     *
     * @param datas
     */
    @Override
    public void showMoreDatas(OfflineDetectionData datas) {
        if (datas.getOffLineTaskList().size() == 0) {
            proOfflineRecycler.setAdapterLastState(RefreshRecycleView.STATE_NO_MORE);
        } else {
            mDatas.addAll(datas.getOffLineTaskList());
            adapter.UpDateList(mDatas);
            adapter.notifyDataSetChanged();
            proOfflineRecycler.setRefreshing(false);
            proOfflineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_LOADEMORE);
        }
        Operation = 0;
    }

    @Override
    public void claimSucceed() {
        toDetail();
    }

    @Override
    public void claimFailed(String msg) {
        SweetAlertDialog dialog = new SweetAlertDialog(OfflineDetectionActivity.this);
        dialog.setTitleText(msg);
        dialog.setConfirmText("关闭");
        dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        dialog.show();
        onRefresh();
    }

    @Override
    public void qiangdan(final String taskId, String msg) {
        SweetAlertDialog dialog = new SweetAlertDialog(OfflineDetectionActivity.this);
        dialog.setTitleText(msg);
        dialog.setConfirmText("确认");
        dialog.setCancelText("取消");
        dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), taskId, "type", "renling", -1);
            }
        });
        dialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        dialog.show();
//        onRefresh();
    }

    @Override
    public void showEmptyView(String msg) {
        dismissDialog();
        if(fastEmptyView!=null&&proOfflineRecycler!=null){
            fastEmptyView.setVisibility(View.VISIBLE);
            proOfflineRecycler.setVisibility(View.GONE);
        }
    }

    @Override
    public void showError(String error) {
        dismissDialog();

        if (error != null) {
            if (error.endsWith("2")) {
                //上拉加载
                //设置最后一行显示加载失败
                proOfflineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
                //设置可以上拉加载
                RefreshRecycleView.isRefresh = false;
            } else {
                //第一次加载
                proOfflineRecycler.setRefreshing(false);//停止显示加载动画
                MyToast.showShort( Constant.errr_net);
            }
        }
    }
    //点击全部状态后和今日任务的回调

    /**
     * @param status1
     * @param position
     */
    @Override
    public void filter_date(int status1, int position) {
        super.filter_date(status1, position);

        //点击的今日任务
        Logger.e("position::::" + position);
        if (filter_date.getId() == status1) {
            if (position == 0) {
                //全部任务
                datetype = Constant.ALL_TASK;
                MobclickAgent.onEvent(OfflineDetectionActivity.this, "pinggushi_xianxiaquanburenwu");//友盟统计
            } else if (position == 1) {
                //今日任务
                datetype = Constant.TODAY_TASK;
                MobclickAgent.onEvent(OfflineDetectionActivity.this, "pinggushi_xianxiajinrirenwu");//友盟统计
            } else if (position == 2) {
                //昨日任务
                datetype = Constant.YESTERDAY_TASK;
                MobclickAgent.onEvent(OfflineDetectionActivity.this, "pinggushi_xianxiazuorirenwu");//友盟统计
            }
            Drawable drawable = getResources().getDrawable(R.drawable.down_arror);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            filter_date.setCompoundDrawables(null, null, drawable, null);//画在右边
        } else {
            //点击了状态筛选
            status = statusData.getItemList().getStatusInfo().getItem().get(position).getId();
            MobclickAgent.onEvent(OfflineDetectionActivity.this, youmeng[position]);//友盟统计
            Drawable drawable = getResources().getDrawable(R.drawable.down_arror);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            filter_status.setCompoundDrawables(null, null, drawable, null);//画在右边
        }
        onRefresh();
    }

}
